﻿//------------------------------------------------------------------------------------------------- 
// <copyright file="PluggableTypeProcessor.cs" company="Christopher Hines">
// Copyright (c) Christopher Hines. All rights reserved.
// </copyright>
// <summary>
//    Registers pluggable types in the instance resolution collection
// </summary>
//-------------------------------------------------------------------------------------------------

namespace Copperfield
{
    using System;
    using System.Linq;

    /// <summary>
    /// Registers pluggable types in the instance resolution collection
    /// </summary>
    internal class PluggableTypeProcessor : IContextProcessor
    {
        /// <summary>
        /// Processes a type accordingly if it is a type of Pluggable Type
        /// </summary>
        /// <param name="type">The type that will be processed</param>
        public void Process(Type type)
        {
            ContextPluggableAttribute attribute;
            if (!TypeUtility.TryGetAttribute(type, out attribute))
            {
                return;
            }
            
            var pluginType = attribute.PluginType;
            var validContexts = attribute.BuildRelatedContextsForType(type).ToList();

            foreach (var context in validContexts)
            {
                PluggableTypeCache.InstanceDictionaryFor(pluginType).Add(context, type);
            }

            if (attribute.DefaultInstance)
            {
                ContextConfigurationFactory.For(pluginType).Named(ContextConfigurationFactory.DefaultInstanceKey).Use(type);
            }
        }
    }
}
